<template>
  <view class="mine-container">
    <!-- 商户信息卡片 -->
    <view class="merchant-card">
      <view class="merchant-header">
        <view class="header-left">
          <image :src="avatar || '/static/images/profile.jpg'" class="avatar" mode="aspectFill"></image>
          <view class="info-box">
            <text class="nick-name">{{ userInfo.nickName || '用户' }}</text>
            <text class="user-id">ID: {{ userInfo.userId }}</text>
          </view>
        </view>
        <view class="edit-btn-wrapper" @click="editInfo">
          <uni-icons type="compose" size="20" color="#fff"></uni-icons>
          <text class="edit-text">编辑</text>
        </view>
      </view>

      <view class="merchant-info">
        <view class="info-item" v-if="userInfo.merchantId">
          <text class="info-label">商户ID:</text>
          <text class="info-value">{{ userInfo.merchantId }}</text>
        </view>
        <view class="info-item" v-if="userInfo.merchantName">
          <text class="info-label">经营名称:</text>
          <text class="info-value">{{ userInfo.merchantName }}</text>
        </view>
        <view class="info-item" v-if="userInfo.merchantCode">
          <text class="info-label">商户编号:</text>
          <text class="info-value">{{ userInfo.merchantCode }}</text>
        </view>
        <view class="info-item" v-if="userInfo.businessAddress">
          <text class="info-label">经营地址:</text>
          <text class="info-value">{{ userInfo.businessAddress }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">所在区域:</text>
          <text class="info-value">{{ userInfo.area || '-' }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">用户账号:</text>
          <text class="info-value">{{ userInfo.userName || '-' }}</text>
        </view>
        <view class="info-item" v-if="!userInfo.merchantId">
          <text class="info-label">所属部门:</text>
          <text class="info-value">{{ userInfo.deptName || '-' }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">用户角色:</text>
          <text class="info-value">{{ userInfo.roleGroup || '-' }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">主要负责人:</text>
          <text class="info-value">{{ userInfo.contactPerson || '-' }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">联系电话:</text>
          <text class="info-value">{{ userInfo.contactPhone || '-' }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">注册时间:</text>
          <text class="info-value">{{ formatDate(userInfo.createTime) }}</text>
        </view>
      </view>

      <view class="qr-code" @click="showQrCode">
        <image v-if="QrCode" :src="QrCode" class="qr-image"></image>
        <view v-else class="qr-placeholder">
          <uni-icons type="scan" size="30" color="#999"></uni-icons>
          <text class="qr-text">点击生成</text>
        </view>
      </view>
    </view>

    <!-- 功能模块 -->
    <view class="menu-sections">
      <!-- 市场管理 -->
      <!-- <view class="menu-section">
        <view class="section-header">
          <view class="section-divider"></view>
          <text class="section-title">市场管理</text>
        </view>
        <view class="menu-list">
          <view class="menu-item" @click="handleMenuItem('switchMarket')">
            <view class="menu-left">
              <uni-icons type="shop" size="24" color="#666"></uni-icons>
              <text class="menu-text">切换市场</text>
            </view>
            <view class="menu-right">
              <text class="current-market">{{ userInfo.deptName || '未绑定' }}</text>
              <uni-icons type="right" size="16" color="#ccc"></uni-icons>
            </view>
          </view>
        </view>
      </view> -->

      <!-- 主体资质 -->
      <view class="menu-section">
        <view class="section-header">
          <view class="section-divider"></view>
          <text class="section-title">主体资质</text>
        </view>
        <view class="menu-list">
          <view class="menu-item" @click="handleMenuItem('businessLicense')">
            <view class="menu-left">
              <uni-icons type="image" size="24" color="#666"></uni-icons>
              <text class="menu-text">营业执照</text>
            </view>
            <view class="menu-right">
              <!-- <view v-if="certificationStatus.businessLicenseStatus === '1'" class="status-tag success">
                <uni-icons type="checkmarkempty" size="14" color="#52c41a"></uni-icons>
                <text class="status-text">已认证</text>
              </view>
              <view v-else-if="certificationStatus.businessLicenseStatus === '0'" class="status-tag warning">
                <uni-icons type="info" size="14" color="#faad14"></uni-icons>
                <text class="status-text">待审核</text>
              </view>
              <view v-else-if="certificationStatus.businessLicenseStatus === '2'" class="status-tag error">
                <uni-icons type="close" size="14" color="#ff4d4f"></uni-icons>
                <text class="status-text">审核失败</text>
              </view>
              <view v-else-if="certificationStatus.businessLicenseUploaded" class="status-tag info">
                <uni-icons type="upload" size="14" color="#1890ff"></uni-icons>
                <text class="status-text">已上传</text>
              </view>
              <view v-else class="status-tag default">
                <uni-icons type="circle" size="14" color="#999"></uni-icons>
                <text class="status-text">未上传</text>
              </view> -->
              <uni-icons type="right" size="16" color="#ccc"></uni-icons>
            </view>
          </view>
          <view class="menu-item" @click="handleMenuItem('idCard')">
            <view class="menu-left">
              <uni-icons type="person" size="24" color="#666"></uni-icons>
              <text class="menu-text">法人身份证</text>
            </view>
            <view class="menu-right">
              <!-- <view v-if="certificationStatus.idcardStatus === '1'" class="status-tag success">
                <uni-icons type="checkmarkempty" size="14" color="#52c41a"></uni-icons>
                <text class="status-text">已认证</text>
              </view>
              <view v-else-if="certificationStatus.idcardStatus === '0'" class="status-tag warning">
                <uni-icons type="info" size="14" color="#faad14"></uni-icons>
                <text class="status-text">待审核</text>
              </view>
              <view v-else-if="certificationStatus.idcardStatus === '2'" class="status-tag error">
                <uni-icons type="close" size="14" color="#ff4d4f"></uni-icons>
                <text class="status-text">审核失败</text>
              </view>
              <view v-else-if="certificationStatus.idcardUploaded" class="status-tag info">
                <uni-icons type="upload" size="14" color="#1890ff"></uni-icons>
                <text class="status-text">已上传</text>
              </view>
              <view v-else class="status-tag default">
                <uni-icons type="circle" size="14" color="#999"></uni-icons>
                <text class="status-text">未上传</text>
              </view> -->
              <uni-icons type="right" size="16" color="#ccc"></uni-icons>
            </view>
          </view>
        </view>
      </view>

      <!-- 质量安全协议功能暂未完全实现，先隐藏 -->
      <!-- <view class="menu-section">
        <view class="section-header">
          <view class="section-divider"></view>
          <text class="section-title">质量安全协议</text>
        </view>
        <view class="menu-list">
          <view class="menu-item" @click="handleMenuItem('safetyAgreement')">
            <view class="menu-left">
              <uni-icons type="upload" size="24" color="#666"></uni-icons>
              <text class="menu-text">质量安全承诺书.pdf</text>
            </view>
            <view class="menu-right">
              <view class="status-tag success">
                <uni-icons type="checkmarkempty" size="14" color="#52c41a"></uni-icons>
                <text class="status-text">已上传</text>
              </view>
              <uni-icons type="right" size="16" color="#ccc"></uni-icons>
            </view>
          </view>
        </view>
      </view> -->

      <!-- 供货者管理 -->
      <view class="menu-section">
        <view class="section-header">
          <view class="section-divider"></view>
          <text class="section-title">供货者管理</text>
        </view>
        <view class="menu-list">
          <view class="menu-item" @click="handleMenuItem('supplierList')">
            <view class="menu-left">
              <uni-icons type="contact" size="24" color="#666"></uni-icons>
              <text class="menu-text">供货者列表</text>
            </view>
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
          <view class="menu-item" @click="handleMenuItem('addSupplier')">
            <view class="menu-left">
              <uni-icons type="personadd" size="24" color="#666"></uni-icons>
              <text class="menu-text">添加供货者</text>
            </view>
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
          <!-- 供货者资质功能暂未实现，先隐藏 -->
          <!-- <view class="menu-item" @click="handleMenuItem('supplierQualification')">
            <view class="menu-left">
              <uni-icons type="list" size="24" color="#666"></uni-icons>
              <text class="menu-text">供货者资质</text>
            </view>
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view> -->
          <!-- <view class="menu-item" @click="handleMenuItem('supplierGoods')">
            <view class="menu-left">
              <uni-icons type="compose" size="24" color="#666"></uni-icons>
              <text class="menu-text">供货商商品配置</text>
            </view>
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view> -->
        </view>
      </view>

      <!-- 车辆管理 -->
      <view class="menu-section">
        <view class="section-header">
          <view class="section-divider"></view>
          <text class="section-title">车辆管理</text>
        </view>
        <view class="menu-list">
          <view class="menu-item" @click="handleMenuItem('vehicleList')">
            <view class="menu-left">
              <uni-icons type="shop" size="24" color="#666"></uni-icons>
              <text class="menu-text">车辆列表</text>
            </view>
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
          <view class="menu-item" @click="handleMenuItem('addVehicle')">
            <view class="menu-left">
              <uni-icons type="circle" size="24" color="#666"></uni-icons>
              <text class="menu-text">添加车辆</text>
            </view>
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
          <view class="menu-item" @click="handleMenuItem('vehicleLicense')">
            <view class="menu-left">
              <uni-icons type="gear" size="24" color="#666"></uni-icons>
              <text class="menu-text">车辆证件</text>
            </view>
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
        </view>
      </view>

      <!-- 系统管理 -->
      <view class="menu-section">
        <view class="section-header">
          <view class="section-divider"></view>
          <text class="section-title">系统管理</text>
        </view>
        <view class="menu-list">
          <view class="menu-item" @click="handleMenuItem('accountSettings')">
            <view class="menu-left">
              <uni-icons type="gear" size="24" color="#666"></uni-icons>
              <text class="menu-text">账户设置</text>
            </view>
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
          <view class="menu-item" @click="handleMenuItem('changePassword')">
            <view class="menu-left">
              <uni-icons type="locked" size="24" color="#666"></uni-icons>
              <text class="menu-text">修改密码</text>
            </view>
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
          <!-- 消息通知功能暂未实现，先隐藏 -->
          <!-- <view class="menu-item" @click="handleMenuItem('notifications')">
            <view class="menu-left">
              <uni-icons type="notification" size="24" color="#666"></uni-icons>
              <text class="menu-text">消息通知</text>
            </view>
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view> -->
          <view class="menu-item" @click="handleMenuItem('helpCenter')">
            <view class="menu-left">
              <uni-icons type="help" size="24" color="#666"></uni-icons>
              <text class="menu-text">帮助中心</text>
            </view>
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
          <view class="menu-item" @click="handleLogout">
            <view class="menu-left">
              <uni-icons type="upload" size="24" color="#ff4d4f"></uni-icons>
              <text class="menu-text" style="color: #ff4d4f">退出登录</text>
            </view>
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
        </view>
      </view>
    </view>

    <!-- 自定义tabbar -->
    <custom-tabbar :current="2" />
  </view>
</template>

<script>
import { getUserProfile, generateQrCode } from '@/api/system/user';
import { certificationStatus, generateMerchantQrCode } from '@/api/system/merchant';
import CustomTabbar from '@/components/custom-tabbar/custom-tabbar';
import storage from '@/utils/storage.js';
import config from '@/config';
const baseUrl = config.baseUrl;

export default {
  components: {
    CustomTabbar,
  },
  data() {
    return {
      merchantName: this.$store.state.user.name || '张三',
      avatar: this.$store.state.user.avatar || '',
      userInfo: {
        userId: '',
        userName: '',
        nickName: '',
        phonenumber: '',
        email: '',
        sex: '',
        deptName: '',
        roleGroup: '',
        createTime: '',
      },
      certificationStatus: {
        overallStatus: '0', // 0-未认证, 1-已认证, 2-认证中, 3-认证失败
        businessLicenseStatus: null,
        businessLicenseUploaded: false,
        idcardStatus: null,
        idcardUploaded: false,
      },
      QrCode: '',
    };
  },
  computed: {},
  onShow() {
    // 隐藏原生tabBar
    uni.hideTabBar();
    // 先加载用户详细信息
    this.loadUserProfile();
    // 加载认证状态
    this.loadCertificationStatus();
  },
  methods: {
    // 处理菜单点击
    handleMenuItem(type) {
      const routes = {
        businessLicense: '/pages/mine/qualification/business',
        idCard: '/pages/mine/qualification/idcard',
        supplierList: '/pages/supplier/list',
        addSupplier: '/pages/supplier/add',
        supplierGoods: '/pages/supplier/goods',
        vehicleList: '/pages/vehicle/list',
        addVehicle: '/pages/vehicle/add',
        vehicleLicense: '/pages/vehicle/list', // 先到列表页选择车辆
        accountSettings: '/pages/mine/setting/index',
        changePassword: '/pages/mine/pwd/index',
        helpCenter: '/pages/mine/help/index',
      };

      const route = routes[type];
      if (route) {
        uni.navigateTo({ url: route });
      } else {
        uni.showToast({ title: '功能开发中', icon: 'none' });
      }
    },

    // 退出登录
    handleLogout() {
      uni.showModal({
        title: '确认退出',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            // 调用store的LogOut action
            this.$store
              .dispatch('LogOut')
              .then(() => {
                storage.clean();
                uni.clearStorageSync();
                // 退出成功后跳转到登录页
                uni.reLaunch({
                  url: '/pages/login',
                });
              })
              .catch((error) => {
                console.error('退出登录失败:', error);
                // 即使退出失败也清理本地数据并跳转
                uni.removeStorageSync('token');
                uni.removeStorageSync('merchantId');
                uni.reLaunch({
                  url: '/pages/login',
                });
              });
          }
        },
      });
    },

    // 编辑信息
    editInfo() {
      uni.navigateTo({ url: '/pages/mine/info/edit' });
    },

    // 加载用户详细信息
    async loadUserProfile() {
      try {
        const response = await getUserProfile();
        if (response.code === 200 && response.data) {
          this.userInfo = response.data;
          // 更新显示的用户名和头像
          this.merchantName = response.data.nickName || response.data.userName || '用户';
          if(response.data.avatar){
            this.avatar = baseUrl + response.data.avatar || '';
          }


          console.log(this.avatar);
          
          if (this.userInfo.merchantId) {
            this.QrCode = this.userInfo.qrCode;
          } else if (this.userInfo.personalQrCode) {
            this.QrCode = this.userInfo.personalQrCode;
          }
        }
      } catch (error) {
        console.error('加载用户信息失败:', error);
      }
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '-';
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 显示个人二维码
    showQrCode() {
      if (!this.QrCode) {
      }
      if (this.QrCode) {
        // 如果已有二维码，显示预览
        uni.previewImage({
          urls: [this.QrCode],
          current: 0,
          longPressActions: {
            itemList: ['保存图片'],
            success: (data) => {
              if (data.tapIndex === 0) {
                this.saveQrCode();
              }
            },
          },
        });
      } else {
        // 如果没有二维码，生成新的
        this.generateQrCode();
      }
    },

    // 生成个人二维码
    async generateQrCode() {
      try {
        uni.showLoading({ title: '生成中...' });
        let response = null;
        if (this.userInfo.merchantId) {
          response = await generateMerchantQrCode({
            Content: 'https://app.anshisu.com/zhjgapp/#/pages/user/merchant-details?merchantId=' + this.userInfo.merchantId,
          });
        } else if (this.userInfo.personalQrCode) {
          response = await generateQrCode();
        }
        if (response.code === 200) {
          this.QrCode = response.qrCode;
          uni.hideLoading();
          uni.showToast({
            title: '生成成功',
            icon: 'success',
          });
        } else {
          uni.hideLoading();
          uni.showToast({
            title: response.msg || '生成失败',
            icon: 'none',
          });
        }
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: '生成失败',
          icon: 'none',
        });
      }
    },

    // 保存二维码到相册
    saveQrCode() {
      if (!this.QrCode) return;

      // #ifdef MP-WEIXIN
      uni.getImageInfo({
        src: this.QrCode,
        success: (res) => {
          uni.saveImageToPhotosAlbum({
            filePath: res.path,
            success: () => {
              uni.showToast({
                title: '保存成功',
                icon: 'success',
              });
            },
            fail: () => {
              uni.showToast({
                title: '保存失败',
                icon: 'none',
              });
            },
          });
        },
      });
      // #endif
    },

    // 加载认证状态
    async loadCertificationStatus() {
      try {
        const response = await certificationStatus();
        if (response.code === 200 && response.data) {
          this.certificationStatus = response.data;
          console.log('认证状态:', this.certificationStatus);
        }
      } catch (error) {
        console.error('加载认证状态失败:', error);
      }
    },
  },
};
</script>

<style scoped>
page {
  background: linear-gradient(180deg, #e8f5e9 0%, #f1f8e9 100%);
}
.mine-container {
  background: linear-gradient(180deg, #e8f5e9 0%, #f1f8e9 100%);
  min-height: 100vh;
  padding-bottom: 120rpx; /* 为自定义tabbar留出空间 */
  padding-top: 1rpx;
}

.header {
  background-color: #fff;
  padding: 20rpx 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
}

.header-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
}

.header-icons {
  display: flex;
  align-items: center;
}

.merchant-card {
  background-color: #3b82f6;
  margin: 50rpx 30rpx 30rpx;
  border-radius: 16rpx;
  padding: 40rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
  position: relative;
}

.merchant-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.header-left {
  display: flex;
  align-items: center;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  border: 4rpx solid #f0f0f0;
}

.info-box {
  margin-left: 20rpx;
  color: #fff;
}
.nick-name {
  font-size: 36rpx;
  font-weight: bold;
  display: block;
}
.user-id {
  font-size: 24rpx;
  font-weight: bold;
  display: block;
  margin-top: 10rpx;
}

.verify-badge {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 36rpx;
  height: 36rpx;
  background-color: #1890ff;
  border-radius: 18rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 3rpx solid #fff;
}

.auth-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-left: 16rpx;
}

.auth-tag {
  display: flex;
  align-items: center;
  font-size: 22rpx;
  padding: 6rpx 12rpx;
  border-radius: 4rpx;
}

.auth-tag-text {
  margin-left: 6rpx;
}

.auth-tag.success {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1rpx solid #b7eb8f;
}

.auth-tag.warning {
  background-color: #fff7e6;
  color: #faad14;
  border: 1rpx solid #ffd591;
}

.auth-tag.error {
  background-color: #fff2f0;
  color: #ff4d4f;
  border: 1rpx solid #ffccc7;
}

.auth-tag.default {
  background-color: #f5f5f5;
  color: #999;
  border: 1rpx solid #d9d9d9;
}

.edit-btn-wrapper {
  display: flex;
  align-items: center;
  padding: 8rpx 16rpx;
  border: 1rpx solid #fff;
  border-radius: 30rpx;
  background-color: rgba(24, 144, 255, 0.05);
  flex-shrink: 0;
}

.edit-text {
  font-size: 24rpx;
  color: #fff;
  margin-left: 6rpx;
}

.merchant-info {
  margin-bottom: 30rpx;
}

.merchant-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #fff;
  margin-bottom: 20rpx;
  display: block;
}

.info-item {
  display: flex;
  margin-bottom: 15rpx;
}

.info-label {
  font-size: 26rpx;
  color: #f2f2f2;
  width: 160rpx;
}

.info-value {
  font-size: 26rpx;
  color: #fff;
  flex: 1;
}

.qr-code {
  position: absolute;
  bottom: 40rpx;
  right: 40rpx;
  width: 140rpx;
  height: 140rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.qr-image {
  width: 100%;
  height: 100%;
}

.qr-placeholder {
  width: 120rpx;
  height: 120rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f9f9f9;
  border-radius: 8rpx;
}

.qr-text {
  font-size: 20rpx;
  color: #999;
  margin-top: 5rpx;
}

.menu-sections {
  padding: 0 30rpx;
}

.menu-section {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
}

.section-header {
  display: flex;
  align-items: center;
  padding: 25rpx 30rpx 15rpx;
}

.section-divider {
  width: 6rpx;
  height: 30rpx;
  background-color: #1890ff;
  border-radius: 3rpx;
  margin-right: 15rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.menu-list {
  padding: 0 0;
}

.menu-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-left {
  min-width: 200rpx;
  display: flex;
  align-items: center;
}

.menu-text {
  font-size: 30rpx;
  color: #333;
  margin-left: 20rpx;
}

.menu-right {
  display: flex;
  align-items: center;
}

.edit-btn:active {
  opacity: 0.8;
}
</style>
